package com.itboye.lottery.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.itboye.bylibrary.util.TimeUtils;
import com.itboye.lottery.R;
import com.itboye.lottery.bean.HotPeoleDetail;
import com.itboye.lottery.dialog.FollowDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 */
public class AdapterFragment extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {

    private Activity context;
    public List<HotPeoleDetail.PlanInfoEntity> mData = new ArrayList<>();
    private LayoutInflater inflater;

    public AdapterFragment(Activity context, List<HotPeoleDetail.PlanInfoEntity> mData) {
        this.context = context;
        this.mData = mData;
        inflater = LayoutInflater.from(context);
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_table, parent, false);
        HotPeopleViewHolder holder = new HotPeopleViewHolder(view);
        return holder;
    }

//    public void refresh(List<ResHotPeopleInfo.HotPeopleOrderBean> datas) {
//        if (mData != null) {
//            mData.clear();
//            addData(datas);
//        }
//    }
//
//
//    public void addData(List<ResHotPeopleInfo.HotPeopleOrderBean> datas) {
//        mData.addAll(datas);
//        notifyDataSetChanged();
//    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        HotPeopleViewHolder viewHolder = (HotPeopleViewHolder) holder;
//        for (int i = 0; i < viewHolder.ll_table.getChildCount(); i++) {
////            if ( i == viewHolder.ll_table.getChildCount() - 1) {
////
////            } else {
//                viewHolder.ll_table.removeViewAt(i);
////            }
//        }
        viewHolder.ll_table.removeAllViews();
        if (mData != null) {
            ((TextView) viewHolder.tablerow_title.getChildAt(1)).setText("主队/客队");
            ((TextView) viewHolder.tablerow_title.getChildAt(2)).setText("投注内容");
            ((TextView) viewHolder.tablerow_title.getChildAt(3)).setText("开奖结果");
            HotPeoleDetail.PlanInfoEntity planInfoEntity = mData.get(position);
            viewHolder.tv_user_name.setText(TimeUtils.getFormatTime(planInfoEntity.getCreate_time() * 1000, "yyyy-MM-dd"));
            viewHolder.item_follow_end_time.setText("截止时间:" + TimeUtils.getFormatTime(planInfoEntity.getEnd_time() * 1000, "MM-dd HH:mm"));
            if (planInfoEntity.getRed_number() <= 0) {
                viewHolder.tv_lianhong.setVisibility(View.GONE);
            } else {
                viewHolder.tv_lianhong.setVisibility(View.VISIBLE);
                viewHolder.tv_lianhong.setText(planInfoEntity.getRed_number() + "连红");
            }
            ((TextView) viewHolder.tb_row_1.getChildAt(0)).setText(planInfoEntity.getTotal_amount() + "元");
            ((TextView) viewHolder.tb_row_1.getChildAt(1)).setText(planInfoEntity.getFollow_num() + "人");
            ((TextView) viewHolder.tb_row_1.getChildAt(2)).setText(planInfoEntity.getCount_amount() + "元");
            viewHolder.tv_follow.setTag(position);
            viewHolder.tv_follow.setTag(R.id.tag_1, 1);
            viewHolder.tv_follow.setOnClickListener(this);
            viewHolder.tv_group_buy_des.setTag(viewHolder);
            viewHolder.tv_group_buy_des.setTag(R.id.tag_1, position);
            viewHolder.tv_group_buy_des.setOnClickListener(this);
            caculateFollowMoney(viewHolder.item_hotpeople_total_money, 1, position);
            JSONObject jsonObject = null;
            String plan = planInfoEntity.getOrigin_num();
            try {
                jsonObject = new JSONObject(plan);
//            switch (public_type) {
//                case 0:
//                    //永久保密
//                    viewHolder.tv_secret.setText(listEntity.getBuy_content());
//                    break;
//                case 1:
//                    //开奖可见
//                    viewHolder.tv_secret.setText(listEntity.getBuy_content());
//                    break;
//                case 2://公开
//                viewHolder.ll_table.removeAllViews();
                HashMap<String, String> hashMap = new HashMap<>();
                if (planInfoEntity.getBall_info() != null) {
                    for (int i = 0; i < planInfoEntity.getBall_info().size(); i++) {
                        View view = View.inflate(context, R.layout.item_row, null);
                        TableRow tablerow_content = view.findViewById(R.id.tablerow_content);
                        HotPeoleDetail.PlanInfoEntity.BallInfoEntity ballInfoEntity = planInfoEntity.getBall_info().get(i);
                        String bDate = ballInfoEntity.getB_date().replaceAll("-", "");
                        String num = ballInfoEntity.getNum_type();
                        JSONObject jsonObject1 = jsonObject.getJSONObject(bDate + num);
                        Iterator<String> iterator = jsonObject1.keys();
                        while (iterator.hasNext()) {
                            StringBuffer stringBufferValue = new StringBuffer();
                            StringBuffer kaijiang = new StringBuffer();
                            String key = iterator.next();
                            hashMap.put(key, key);
                            JSONObject jsonObjectValue = jsonObject1.getJSONObject(key);
                            Iterator<String> iterator2 = jsonObjectValue.keys();
                            // 3010: 胜平负
                            // 3006:让球胜平负
                            // 3007: 全场比分(90分钟)
                            // 3008: 进球数
                            // 3009: 半全场胜负  这个暂时不支持
                            // 3011: 混合过关 （一注投注中包含2个玩法以上的就是混合过关）

                            switch (key) {
                                case "3010":
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        if (key2.equals("0")) {
                                            stringBufferValue.append("主负,");
                                        }
                                        if (key2.equals("1")) {
                                            stringBufferValue.append("主平,");
                                        }
                                        if (key2.equals("3")) {
                                            stringBufferValue.append("主胜,");
                                        }
                                    }
                                    if (ballInfoEntity.getFinal_score() != null || "null".equals(ballInfoEntity.getFinal_score())) {
                                        if (Integer.valueOf(ballInfoEntity.getFinal_score().toString().split(":")[0]) > Integer.valueOf(ballInfoEntity.getFinal_score().toString().split(":")[1])) {
                                            //主胜
                                            kaijiang.append("主胜,");
                                        } else if (Integer.valueOf(ballInfoEntity.getFinal_score().toString().split(":")[0]) == Integer.valueOf(ballInfoEntity.getFinal_score().toString().split(":")[1])) {
                                            //主胜
                                            kaijiang.append("主平,");
                                        } else if (Integer.valueOf(ballInfoEntity.getFinal_score().toString().split(":")[0]) < Integer.valueOf(ballInfoEntity.getFinal_score().toString().split(":")[1])) {
                                            //主胜
                                            kaijiang.append("主负,");
                                        }
                                    }
                                    break;
                                case "3007": //让球胜平负
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        if (!key2.equals("single")) {
                                            JSONObject value = jsonObjectValue.getJSONObject(key2);//种类所带表的赔率
                                            Iterator<String> iterator3 = value.keys();
                                            while (iterator3.hasNext()) {
                                                String key3 = iterator3.next();
                                                stringBufferValue.append(key3.substring(0, 1) + ":" + key3.substring(1, 2) + ",");
                                            }
                                        }
                                    }
                                    if (ballInfoEntity.getFinal_score() != null || "null".equals(ballInfoEntity.getFinal_score())) {
                                        kaijiang.append(ballInfoEntity.getFinal_score() + ",");
                                    }
                                    break;
                                case "3006":
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        if (!key2.equals("single")) {
                                            if (key2.equals("0")) {
                                                stringBufferValue.append("让负,");
                                            }
                                            if (key2.equals("1")) {
                                                stringBufferValue.append("让平,");
                                            }
                                            if (key2.equals("3")) {
                                                stringBufferValue.append("让胜,");
                                            }
                                        }
                                    }
                                    if (!TextUtils.isEmpty(ballInfoEntity.getFinal_score()+"")) {
                                        kaijiang.append(ballInfoEntity.getFinal_score() + ",");
                                    }
                                    break;
                                case "3008":
                                    //总进球
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
//                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        if (key2.equals("goals")) {
                                            JSONObject jsonObject2 = jsonObjectValue.getJSONObject(key2);
                                            Iterator<String> iterator1 = jsonObject2.keys();
                                            while (iterator1.hasNext()) {
                                                String key1 = iterator1.next();//投注种类中所代表的种类
//                                                String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                                stringBufferValue.append(key1 + "球,");
                                            }
//                                            for (int i1 = 0; i1 < jsonArray.length(); i1++) {
//                                                stringBufferValue.append(jsonArray.get(i) + "球,");
//                                            }
                                        }
                                    }
                                    if (ballInfoEntity.getFinal_score() != null || "null".equals(ballInfoEntity.getFinal_score())) {
                                        kaijiang.append(Integer.valueOf(ballInfoEntity.getFinal_score().toString().split(":")[0]) + Integer.valueOf(ballInfoEntity.getFinal_score().toString().split(":")[1]) + "球,");
                                    }
                                    break;
                                case "3009":
                                    //半全场
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        if (!key2.equals("single")) {
                                            stringBufferValue.append(key2.replaceAll("3", "胜").replaceAll("1", "平").replaceAll("0", "负") + ",");
                                        }
                                    }
                                    break;

                                //-------------------------篮球相关---------------
                                case "3001"://胜负
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        String sfValue = "";
                                        if (key2.equals("0")) {
                                            sfValue = "让客胜";
                                        }
                                        if (key2.equals("3")) {
                                            sfValue = "让主胜";
                                        }
                                        if (!TextUtils.isEmpty(sfValue)) {
                                            stringBufferValue.append(sfValue );
                                            stringBufferValue.append(",");
                                        }
                                    }
                                    break;
                                case "3002"://让胜负
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        String rsfValue = "";
                                        if (key2.equals("0")) {
                                            rsfValue = "客胜";
                                        }
                                        if (key2.equals("3")) {
                                            rsfValue = "主胜";
                                        }
                                        if (!TextUtils.isEmpty(rsfValue)) {
                                            stringBufferValue.append(rsfValue);
                                            stringBufferValue.append(",");
                                        }
                                    }
                                    break;
                                case "3003": //胜负差
                                    boolean hasAdLHead = false, hasAdWHead = false;
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        String sfcValue = "";
                                        if (key2.startsWith("l")) {
                                            if (!hasAdLHead) {
                                                hasAdLHead = true;
                                                sfcValue = "客胜";
                                                stringBufferValue.append("客胜");
                                            }
                                            if (key2.equals("l1")) {
                                                sfcValue = "[1-5]";
                                            }
                                            if (key2.equals("l2")) {
                                                sfcValue = "[6-10]";
                                            }
                                            if (key2.equals("l3")) {
                                                sfcValue = "[11-15]";
                                            }
                                            if (key2.equals("l4")) {
                                                sfcValue = "[16-20]";
                                            }
                                            if (key2.equals("l5")) {
                                                sfcValue = "[21-25]";
                                            }
                                            if (key2.equals("l6")) {
                                                sfcValue = "[26+]";
                                            }
                                        } else if (key2.startsWith("w")) {
                                            if (!hasAdWHead) {
                                                hasAdWHead = true;
                                                stringBufferValue.append("主胜");
                                                sfcValue = "主胜";
                                            }
                                            if (key2.equals("w1")) {
                                                sfcValue = "[1-5]";
                                            }
                                            if (key2.equals("w2")) {
                                                sfcValue = "[6-10]";
                                            }
                                            if (key2.equals("w3")) {

                                                sfcValue = "[11-15]";
                                            }
                                            if (key2.equals("w4")) {

                                                sfcValue = "[16-20]";
                                            }
                                            if (key2.equals("w5")) {
                                                sfcValue = "[21-25]";
                                            }
                                            if (key2.equals("w6")) {
                                                sfcValue = "[26+]";
                                            }
                                        }

                                        if (!TextUtils.isEmpty(sfcValue)) {
                                            stringBufferValue.append(sfcValue );
                                            stringBufferValue.append(",");
                                        }
                                    }
                                    break;
                                case "3004":
                                    while (iterator2.hasNext()) {
                                        String key2 = iterator2.next();//投注种类中所代表的种类
                                        String value = jsonObjectValue.getString(key2);//种类所带表的赔率
                                        String dxfValue = "";
                                        if (key2.equals("0")) {
                                            dxfValue = "小分";
                                        }
                                        if (key2.equals("1")) {
                                            dxfValue = "大分";
                                        }
//                                        //预设总分
//                                        if (key2.equals("score")) {
//                                            stringBufferValue.append("预设分(" + value + ")<br />");
//                                        }
                                        if (!TextUtils.isEmpty(dxfValue)) {
                                            stringBufferValue.append(dxfValue );
                                            stringBufferValue.append(",");
                                        }
                                    }
                                    break;
                                case "3011":
                                    break;
                            }
                            ((TextView) tablerow_content.getChildAt(3)).setText(planInfoEntity.getIs_result().equals("0") ? "待开奖" : (kaijiang.toString().endsWith(",") ? kaijiang.toString().substring(0, kaijiang.length() - 1) : kaijiang));//开奖结果
                            if (planInfoEntity.getPublic_type().equals("2")) {//永久可见
                                ((TextView) tablerow_content.getChildAt(2)).setText((stringBufferValue.toString().endsWith(",") ? (stringBufferValue.toString().substring(0, stringBufferValue.length() - 1)) : stringBufferValue));
                            }else if(planInfoEntity.getPublic_type().equals("0")){//永久保密
                                ((TextView) tablerow_content.getChildAt(2)).setText("保密");
                            }

                            if(planInfoEntity.getPublic_type().equals("1")&&planInfoEntity.getIs_result().equals("0")){//开奖后可见
                                ((TextView) tablerow_content.getChildAt(2)).setText("开奖前保密");
                            }else if(planInfoEntity.getPublic_type().equals("1")&&planInfoEntity.getIs_result().equals("1")){
                                ((TextView) tablerow_content.getChildAt(2)).setText((stringBufferValue.toString().endsWith(",") ? (stringBufferValue.toString().substring(0, stringBufferValue.length() - 1)) : stringBufferValue));
                            }
                        }

                        ((TextView) tablerow_content.getChildAt(0)).setText(ballInfoEntity.getNum());
                        ((TextView) tablerow_content.getChildAt(1)).setText(ballInfoEntity.getH_cn() + "/" + ballInfoEntity.getA_cn());
                        viewHolder.ll_table.addView(view, viewHolder.ll_table.getChildCount() - 1);
                    }
                    if (hashMap.size() > 1) {//混合
                        if(planInfoEntity.getLottery_type().equals("1")) {
                            viewHolder.tv_lottery_type.setText("足球混合投注");
                        }
                        else if(planInfoEntity.getLottery_type().equals("2")) {
                            viewHolder.tv_lottery_type.setText("篮球混合投注");
                        }
                    } else if (hashMap.size() == 1) {//单种投注
                        if (hashMap.containsKey("3010")) {
                            viewHolder.tv_lottery_type.setText("胜平负");
                        } else if (hashMap.containsKey("3006")) {
                            viewHolder.tv_lottery_type.setText("让球胜平负");

                        } else if (hashMap.containsKey("3007")) {
                            viewHolder.tv_lottery_type.setText("全场比分");

                        } else if (hashMap.containsKey("3008")) {
                            viewHolder.tv_lottery_type.setText("进球数");

                        } else if (hashMap.containsKey("3009")) {
                            viewHolder.tv_lottery_type.setText("半场胜平负");

                        } else if (hashMap.containsKey("3011")) {
                            viewHolder.tv_lottery_type.setText("足球混合投注");

                        }else if (hashMap.containsKey("3001")) {
                            viewHolder.tv_lottery_type.setText("让分胜负");
                        }else if (hashMap.containsKey("3002")) {
                            viewHolder.tv_lottery_type.setText("非让分胜负");
                        }else if (hashMap.containsKey("3003")) {
                            viewHolder.tv_lottery_type.setText("胜负差");

                        }else if (hashMap.containsKey("3004")) {
                            viewHolder.tv_lottery_type.setText("大小分");

                        }
//                                viewHolder.tv_lottery_type.setText("足球混合投注");
                    }

//                    }
//                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        holder.textView.setText(str);
    }

    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }


    private void caculateFollowMoney(TextView textView, int multiple, int position) {
        textView.setText(multiple * Float.parseFloat(mData.get(position).getSingle_amount()) + "元");
    }

    @Override
    public void onClick(View view) {
        int position = 0;
        switch (view.getId()) {
            case R.id.tv_follow:
                position = (int) view.getTag();
                int multiple = (int) view.getTag(R.id.tag_1);
                HotPeoleDetail.PlanInfoEntity listEntity = mData.get(position);
                FollowDialog followDialog = new FollowDialog(context, true);
                followDialog.setEntity(listEntity.getId(), listEntity.getLow_amount(), listEntity.getSingle_amount());
                followDialog.setMultiple(multiple);
                followDialog.show();
                break;
            case R.id.tv_group_buy_des:
                HotPeopleViewHolder viewHolder = (HotPeopleViewHolder) view.getTag();
                position = (int) view.getTag(R.id.tag_1);
                showInputDialog(viewHolder.tv_group_buy_des, viewHolder.item_hotpeople_total_money, viewHolder.tv_follow, position);
                break;
        }
    }


    private void showInputDialog(final TextView ed, final TextView item_hotpeople_total_money, TextView textView, final int position) {
        AlertDialog.Builder alert = new AlertDialog.Builder(context);
        alert.setTitle("输入倍数");
        View view = View.inflate(context, R.layout.alert_x, null);
        final EditText editText = view.findViewById(R.id.edit_content);
        editText.setText(ed.getText());
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        editText.setHint("请输入倍数");
        alert.setView(view);
        alert.setPositiveButton("确认", (dialogInterface, i) -> {
            ed.setText(editText.getText());
            ed.setTag(editText.getText());
            textView.setTag(R.id.tag_1, Integer.parseInt(editText.getText().toString()));
            caculateFollowMoney(item_hotpeople_total_money, Integer.parseInt(editText.getText().toString()), position);
        });
        alert.setNegativeButton("取消", (dialogInterface, i) -> {

        });
        alert.create().show();
    }


    public class HotPeopleViewHolder extends RecyclerView.ViewHolder {

        TextView tv_user_name;
        TextView item_follow_end_time, tv_lottery_type;
        TableRow tb_row_1, tablerow_title;
        TableLayout ll_table;
        TextView mTvGroupBuyMoney;

        TextView mTvFollowNumber;

        TextView mTvFollow;

        TextView mRlAwardNumber, tv_jiangjin, tv_danbeijine;
        RelativeLayout mRlAwardBg;
        View view;
        RelativeLayout rl_bei;
        ImageView iv_type;
        TextView item_hotpeople_total_money;
        LinearLayout beizhu;
        TextView tv_follow, tv_group_buy_des, item_hotpeople_beishu, tv_lianhong;

        public HotPeopleViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            tv_user_name = itemView.findViewById(R.id.tv_user_name);
            item_follow_end_time = itemView.findViewById(R.id.item_follow_end_time);
            tb_row_1 = itemView.findViewById(R.id.tb_row_1);
            ll_table = itemView.findViewById(R.id.ll_table);
            tv_lottery_type = itemView.findViewById(R.id.tv_lottery_type);
            tablerow_title = itemView.findViewById(R.id.tablerow_title);
            tv_follow = itemView.findViewById(R.id.tv_follow);
            tv_group_buy_des = itemView.findViewById(R.id.tv_group_buy_des);
            item_hotpeople_beishu = itemView.findViewById(R.id.item_hotpeople_beishu);
            tv_lianhong = itemView.findViewById(R.id.tv_lianhong);
//            mTvFollow = itemView.findViewById(R.id.tv_follow);
//            mRlAwardNumber = itemView.findViewById(R.id.rl_award_number);
//            mRlAwardBg = itemView.findViewById(R.id.rl_award_bg);
//            rl_bei = itemView.findViewById(R.id.rl_bei);
            item_hotpeople_total_money = itemView.findViewById(R.id.item_hotpeople_total_money);
//            tv_jiangjin = itemView.findViewById(R.id.tv_jiangjin);
//            tv_danbeijine = itemView.findViewById(R.id.tv_danbeijine);
//            beizhu = itemView.findViewById(R.id.beizhu);
        }
    }

}
